import {getMessageBoxByOwnerAndId} from "../db/MessageBoxDB";
import message from "./Message";

abstract class MessageBox{
    protected _emailOwner: string;
    protected _userId: string;

    protected constructor(emailOwner: string, userId: string) {
        this._emailOwner = emailOwner;
        this._userId = userId;
    }

    public async insertNewMessage(messageType:string,senderId:string,context:string,userName:string,originSender:string)
    {
        const MessageBoxDB = getMessageBoxByOwnerAndId(this._emailOwner,this._userId);
        await MessageBoxDB?.create({
            message: new message(senderId,messageType,context,userName),
            read:false
        })
    }

    public async getNewMessage() {
        const MessageBoxDB = getMessageBoxByOwnerAndId(this._emailOwner,this._userId);
        
        if (!MessageBoxDB) {
            throw new Error('Message box not found.');
        }
    
        const unreadMessages = await MessageBoxDB.find({ read: false });
        // 更新未读消息为已读
        if (unreadMessages.length > 0) {
            await MessageBoxDB.updateMany(
                { read: false }, 
                { $set: { read: true } }
            );
        }
    
        return unreadMessages; // 返回未读消息
    }

}

export default MessageBox;